<html>  
  <head>  
        <meta charset="utf-8">  
        <title>5.4.1 柱形图的坐标轴</title>  
  </head> 
  <style>
  
.axis path,
.axis line{
	fill: none;
	stroke: black;
	shape-rendering: crispEdges;
}
 
.axis text {
	font-family: sans-serif;
	font-size: 11px;
}

  </style>
<body>

<script src="../../d3/d3.min.js" charset="utf-8"></script> 
<script>  

var dataset = [50, 43, 120, 87, 99, 167, 142];

var width  = 400;	//SVG绘制区域的宽度
var height = 400;	//SVG绘制区域的高度
	
var svg = d3.select("body")			//选择<body>
			.append("svg")			//在<body>中添加<svg>
			.attr("width", width)	//设定<svg>的宽度属性
			.attr("height", height);//设定<svg>的高度属性
			
//x轴宽度
var xAxisWidth = 300;

//y轴宽度
var yAxisWidth = 300;
			
//x轴比例尺
var xScale = d3.scale.ordinal()
				.domain(d3.range(dataset.length))
				.rangeRoundBands([0,xAxisWidth],0.2);

//y轴比例尺
var yScale = d3.scale.linear()
				.domain([0,d3.max(dataset)])
				.range([0,yAxisWidth]);			
	
//外边框
var padding = { top: 30 , right: 30, bottom: 30, left: 30 };

var rect = svg.selectAll("rect")
				.data(dataset)		//绑定数据
				.enter()			//获取enter部分
				.append("rect")	//添加rect元素，使其与绑定数组的长度一致
				.attr("fill","steelblue")		//设置颜色为steelblue
				.attr("x", function(d,i){		//设置矩形的x坐标
					return padding.left + xScale(i);
				})
				.attr("y", function(d){		//设置矩形的y坐标
					return height- padding.bottom - yScale(d);
				})
				.attr("width",xScale.rangeBand())		//设置矩形的宽度
				.attr("height",function(d){	//设置矩形的高度
					return yScale(d);
				});
				
var text = svg.selectAll("text")
				.data(dataset)			//绑定数据
				.enter()				//获取enter部分
				.append("text")			//添加text元素，使其与绑定数组的长度一致
				.attr("fill","white")
				.attr("font-size","14px")
				.attr("text-anchor","middle")
				.attr("x", function(d,i){
					return padding.left + xScale(i);
				})
				.attr("y", function(d){
					return height- padding.bottom - yScale(d);
				})
				.attr("dx",xScale.rangeBand()/2)
				.attr("dy","1em")
				.text(function(d){
					return d;
				});

var xAxis = d3.svg.axis()
				.scale(xScale)
				.orient("bottom");

yScale.range([yAxisWidth,0]);
				
var yAxis = d3.svg.axis()
				.scale(yScale)
				.orient("left");
				
svg.append("g")
		.attr("class","axis")
		.attr("transform","translate(" + padding.left + "," + (height - padding.bottom) +  ")")
		.call(xAxis);
			
svg.append("g")
		.attr("class","axis")
		.attr("transform","translate(" + padding.left + "," + (height - padding.bottom - yAxisWidth) +  ")")
		.call(yAxis); 
	
</script> 

</body>

</html>